# js101_rule.py
import sys
from pathlib import Path

# 获取 template 目录的绝对路径（根据实际结构调整）
current_file = Path(__file__)
template_dir = current_file.parent.parent  # 上两级目录


sys.path.append(str(template_dir))

# 现在可以正常导入
from utils import date_offset_handler,date_handler
from base_rule import BaseRule
from DataProcessor import DataProcessor
import random
import pandas as pd


class JS101Rule(BaseRule):
    REQUIRED_FIELDS={
        ""
        "设计坐标(X,Y)": "设计坐标(X,Y)",
        "施工部位": "施工部位",
        "施工日期": "施工日期",  
    }
    
    def __init__(self, project_info):
        super().__init__("JS101", project_info)

        # 添加字段
        self.add_field("桩号、部位", lambda _: self.project_info['施工部位'])
        self.add_field("桩号、部位1", lambda _: self.project_info['施工部位'] + '1')
        self.add_field("桩号、部位2", lambda _: self.project_info['施工部位'] + '2')
        self.add_field("桩号、部位3", lambda _: self.project_info['施工部位'] + '3')
        self.add_field("桩号、部位4", lambda _: self.project_info['施工部位'] + '4')
        self.add_field("检测、记录日期", date_handler(0), data_type="date", format="%Y年%m月%d日")
        self.add_field("施工日期", date_handler(0), data_type="date", format="%Y年%m月%d日")
            # 设计坐标
        instance_values = project_info.get("instance_values", {})
        center_x, center_y = instance_values.get("设计坐标(X,Y)","待补充初始设计坐标(X,Y)")
        length = project_info["长"]
        width = project_info["宽"]

        # 分别计算四个理论角点
        half_len = length / 2
        half_wid = width / 2

        theoretical_points = [
            (center_x - half_wid, center_y + half_len),  # A 左上
            (center_x + half_wid, center_y + half_len),  # B 右上
            (center_x + half_wid, center_y - half_len),  # C 右下
            (center_x - half_wid, center_y - half_len),  # D 左下
        ]

        # 生成每个点的随机 X/Y 偏差（例如 ±5）
        deviation_range = (0, 7)
        deviations = [(random.randint(*deviation_range), random.randint(*deviation_range)) for _ in range(4)]

        # 实际坐标 = 理论坐标 - 偏差
        actual_points = [
            (round(theoretical_points[i][0] - dev[0]/1000, 3),
            round(theoretical_points[i][1] - dev[1]/1000, 3))
            for i, dev in enumerate(deviations)
        ]
        def make_lambda(value):
            return lambda _: str(value)

        # 写入字段
        for i, ((x_theory, y_theory), (x_dev, y_dev), (x_actual, y_actual)) in enumerate(
            zip(theoretical_points, deviations, actual_points), start=1
        ):
            self.add_field(f"设计坐标{i}(X)", make_lambda(x_theory), data_type="string", target_cells=[f"B{i+10}"])
            self.add_field(f"设计坐标{i}(Y)", make_lambda(y_theory), data_type="string", target_cells=[f"C{i+10}"])
            self.add_field(f"X轴偏位{i}", make_lambda(x_dev), data_type="string", target_cells=[f"D{i+10}"])
            self.add_field(f"Y轴偏位{i}", make_lambda(y_dev), data_type="string", target_cells=[f"E{i+10}"])
            self.add_field(f"实际坐标{i}(X)", make_lambda(x_actual), data_type="string", target_cells=[f"F{i+10}"])
            self.add_field(f"实际坐标{i}(Y)", make_lambda(y_actual), data_type="string", target_cells=[f"G{i+10}"])
    
    def process(self,**kwargs):
        """
        封装处理逻辑，直接返回结果
        :param data_file_path: 数据文件路径（Excel/CSV）
        :return: 处理后的 DataFrame
        """
        data_file_path=current_file.parent / '模板数据.xlsx'
        df = pd.read_excel(data_file_path)
        rules = self.get_rules()

        processor = DataProcessor(base_data=df, project_info=self.project_info, rules=rules)
        results = processor.process_dataframe(df)

        return results


    def validate_project_info(self, project_info):
        """
        校验 project_info 是否包含所有必需字段。
        :param project_info: 项目信息字典
        :raises ValueError: 缺少字段时抛出异常，提示 sheet 名和字段名
        """
        missing_fields = []
        for field, sheet_name in self.REQUIRED_FIELDS.items():
            if field not in project_info or project_info[field] is None:
                missing_fields.append((sheet_name, field))

        if missing_fields:
            error_messages = [f"[{sheet}] 缺少必要字段：{field}" for sheet, field in missing_fields]
            raise ValueError("\n".join(error_messages))

if __name__ == "__main__":
    PROJECT_BASE_INFO ={
    '施工单位':'浙江交工宏途交通建设有限公司',
    '监理单位':'浙江浙中建设工程管理有限公司',
    '单位工程':'路基工程',
    '分部工程':'涵洞、通道',
    '分项工程':'主体结构',
    '施工日期':'2024/05/31',
    '施工部位':'K59+639圆管涵',
    '设计坐标(X,Y)':(3243273.926,509154.842),
    '长':44.5,#圆管涵长度
    '宽':4,#圆管涵宽度
    '基础宽度':2759,
    '基础厚度':300,
    '基础顶高程':66035,
    '设计高程':66,#基础高程
    '断面尺寸长度':1250,
    '断面尺寸宽度':275.9,
    '断面尺寸高(厚)度':30,
    '基础混凝土强度（砂浆）等级':'C25',
    '基础设计混凝土（砂浆）用量':'15',
    '基础实际混凝土（砂浆）用量':'16',
    '护壁混凝土强度（砂浆）等级':'C25',
    '护壁设计混凝土（砂浆）用量':'15',
    '护壁实际混凝土（砂浆）用量':'16',
} 

    rule = JS101Rule(PROJECT_BASE_INFO)
    results = rule.process()
    print(results)
    
    